const Koa = require('koa')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const session = require('koa-session2')
const bodyParser = require('koa-bodyparser')
const cors = require('koa2-cors')
const json = require('koa-json')
const serve = require('koa-static-server')
const app = new Koa()

// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
const settings = require('./settings')
const Store = require('./interface/utils/store')
const user = require('./interface/user')
const classification = require('./interface/classification')
const news = require('./interface/news')
const publicRoute = require('./interface/public')
const test = require('./interface/test')
const author = require('./interface/author')
const contribution = require('./interface/contribution')
const admin = require('./interface/admin')
const passport = require('./interface/utils/passport')
config.dev = app.env !== 'production'

app.use(
  cors({
    // origin: 'http://localhost:8080',
    // maxAge: 5, // 指定本次预检请求的有效期，单位为秒。
    // credentials: true, // 是否允许发送Cookie
    // allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], // 设置所允许的HTTP请求方法
    // allowHeaders: ['Content-Type', 'Authorization', 'Accept'], // 设置服务器支持的所有头信息字段
    // exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'] // 设置获取其他自定义字段
  })
)

app.use(
  bodyParser({
    extendTypes: ['json', 'form', 'text']
  })
)
// app.use(bodyParser())
// eslint-disable-next-line require-await
// app.use(async (ctx) => {
//   ctx.body = ctx.request.body
// })
app.use(
  serve({
    rootDir: 'static',
    rootPath: '/static'
  })
)

app.keys = ['InformationYouth', 'keys']
app.proxy = true
app.use(
  session({
    key: 'InformationYouth',
    /**  cookie的key。 (默认是 koa:sess) */
    prefix: 'InformationYouth:uid',
    maxAge: 1000 * 60 * 60 * 24 * 7,
    /**  session 过期时间，以毫秒ms为单位计算 。 */
    autoCommit: true,
    /** 自动提交到响应头。(默认是 true) */
    overwrite: false,
    /** 是否允许重写 。(默认是 true) */
    httpOnly: false,
    /** 是否设置HttpOnly，如果在Cookie中设置了"HttpOnly"属性，那么通过程序(JS脚本、Applet等)将无法读取到Cookie信息，这样能有效的防止XSS攻击。  (默认 true) */
    signed: true,
    /** 是否签名。(默认是 true) */
    rolling: true,
    /** 是否每次响应时刷新Session的有效期。(默认是 false) */
    renew: true,
    /** 是否在Session快过期时刷新Session的有效期。(默认是 false) */
    store: new Store()
  })
)
app.use(json())
app.use(passport.initialize())
app.use(passport.session())
async function start() {
  // Instantiate nuxt.js
  const nuxt = new Nuxt(config)

  const {
    host = settings.APP__HOST || process.env.HOST || '127.0.0.1',
    port = settings.APP__PORT || process.env.PORT || 3000
  } = nuxt.options.server

  // Build in development
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  } else {
    await nuxt.ready()
  }
  app.use(user.routes()).use(user.allowedMethods())
  app.use(classification.routes()).use(classification.allowedMethods())
  app.use(publicRoute.routes()).use(publicRoute.allowedMethods())
  app.use(news.routes()).use(news.allowedMethods())
  app.use(admin.routes()).use(admin.allowedMethods())
  app.use(test.routes()).use(test.allowedMethods())
  app.use(author.routes()).use(author.allowedMethods())
  app.use(contribution.routes()).use(contribution.allowedMethods())

  app.use((ctx) => {
    ctx.status = 200
    ctx.respond = false // Bypass Koa's built-in response handling
    ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
    nuxt.render(ctx.req, ctx.res)
  })

  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  })
}

start()
